// ignore_for_file: prefer_const_constructors

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/cart_item.dart';
import 'package:multi_shop/models/order_item.dart';
import 'package:multi_shop/services/cart_api.dart';

/// 购物车页面示例（ShoppingCart）
class ShoppingCart extends StatefulWidget {
  const ShoppingCart({Key? key}) : super(key: key);

  @override
  State<ShoppingCart> createState() => _ShoppingCartState();
}

class _ShoppingCartState extends State<ShoppingCart> {
  // 模拟购物车数据
  final List<CartItem> _items = [];

  bool editing = false; // 是否处于管理模式

  // 计算
  double get selectedTotal => _items
      .where((e) => e.selected)
      .fold(0.0, (sum, e) => sum + e.price * e.quantity);

  int get selectedCount => _items.where((e) => e.selected).length;

  bool get allSelected => _items.isNotEmpty && _items.every((e) => e.selected);

  final _api = CartApi();

  @override
  void initState() {
    super.initState();
    _loadList();
  }

  // 加载列表
  Future<void> _loadList() async {
    final list = await _api.getList();
    debugPrint('购物车列表: $list');
    setState(() {
      _items.addAll(list);
    });
  }

  void _toggleAll(bool v) {
    setState(() {
      for (final it in _items) {
        it.selected = v;
      }
    });
  }

  void _confirmDeleteSelected() {
    if (selectedCount == 0) return;
    // 收集选中商品的 ID
    final selectedIds = _items
        .where((item) => item.selected)
        .map((item) => item.id)
        .toList();

    Get.defaultDialog(
      title: '删除确认',
      middleText: '确定删除选中的 $selectedCount 件商品吗？',
      textCancel: '取消',
      textConfirm: '删除',
      onConfirm: () async {
        await CartApi().delete(selectedIds);
        setState(() {
          _items.removeWhere((e) => e.selected);
        });
        Get.back();
        if (_items.isEmpty) editing = false;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final hasData = _items.isNotEmpty;

    return Scaffold(
      appBar: AppBar(
        title: Text('购物车'),
        elevation: 0,
        actions: [
          if (hasData)
            TextButton(
              onPressed: () => setState(() => editing = !editing),
              child: Text(editing ? '完成' : '管理'),
            ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: !hasData
                ? Center(child: Text('购物车是空的'))
                : ListView.separated(
                    itemCount: _items.length,
                    separatorBuilder: (_, __) => Divider(
                      height: 1,
                      color: Colors.grey.withValues(alpha: 0.1),
                    ),
                    itemBuilder: (context, index) {
                      final item = _items[index];
                      return Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 8,
                        ),
                        child: GestureDetector(
                          onTap: () {
                            Get.toNamed('/detail', arguments: item.productId);
                          },
                          child: Row(
                            children: [
                              // 勾选
                              Checkbox(
                                value: item.selected,
                                onChanged: (v) =>
                                    setState(() => item.selected = v ?? false),
                              ),
                              // 缩略图
                              ClipRRect(
                                borderRadius: BorderRadius.circular(6),
                                child: Image.network(
                                  item.goods?.imageUrl ?? '',
                                  width: 80,
                                  height: 80,
                                  fit: BoxFit.cover,
                                  errorBuilder: (_, __, ___) => Container(
                                    width: 80,
                                    height: 80,
                                    color: Colors.grey.withValues(alpha: 0.15),
                                    child: Icon(Icons.broken_image),
                                  ),
                                ),
                              ),
                              SizedBox(width: 12),
                              // 名称与价格
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      item.goods?.name ?? '',
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    SizedBox(height: 8),
                                    Text(
                                      "¥${item.price.toStringAsFixed(2)}",
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.redAccent,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 数量调整
                              Row(
                                children: [
                                  IconButton(
                                    icon: Icon(Icons.remove_circle_outline),
                                    onPressed: () async {
                                      if (item.quantity > 1) {
                                        setState(() {
                                          item.quantity--;
                                        });
                                        await CartApi().update(
                                          item.id ?? 0,
                                          item.quantity,
                                        );
                                      }
                                    },
                                  ),
                                  Text("${item.quantity}"),
                                  IconButton(
                                    icon: Icon(Icons.add_circle_outline),
                                    onPressed: () async {
                                      setState(() {
                                        item.quantity++;
                                      });
                                      await CartApi().update(
                                        item.id ?? 0,
                                        item.quantity,
                                      );
                                    },
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
          ),

          // 底部栏
          SafeArea(
            top: false,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              color: Colors.white,
              child: Row(
                children: [
                  // 全选
                  InkWell(
                    onTap: () => _toggleAll(!allSelected),
                    child: Row(
                      children: [
                        Checkbox(
                          value: allSelected,
                          onChanged: hasData
                              ? (v) => _toggleAll(v ?? false)
                              : null,
                        ),
                        const Text('全选'),
                      ],
                    ),
                  ),
                  const SizedBox(width: 8),

                  // 中间占位/合计
                  if (!editing) ...[
                    Expanded(
                      child: RichText(
                        text: TextSpan(
                          text: '合计: ',
                          style: DefaultTextStyle.of(
                            context,
                          ).style.copyWith(fontSize: 15),
                          children: [
                            TextSpan(
                              text: '¥${selectedTotal.toStringAsFixed(2)}',
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.redAccent,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ] else
                    Expanded(child: SizedBox()),

                  // 右侧按钮（管理模式：删除；普通模式：去结算）
                  SizedBox(
                    height: 40,
                    child: editing
                        ? ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.redAccent,
                            ),
                            onPressed: selectedCount > 0
                                ? _confirmDeleteSelected
                                : null,
                            child: Text(
                              '删除(${selectedCount})',
                              style: TextStyle(
                                fontSize: 16,
                                color: selectedCount > 0
                                    ? Colors.white
                                    : Colors.grey,
                              ),
                            ),
                          )
                        : ElevatedButton(
                            onPressed: selectedCount > 0
                                ? () {
                                    final selected = _items
                                        .where((e) => e.selected)
                                        .toList();

                                    final orderItems = selected
                                        .map(
                                          (c) => OrderItem(
                                            goodsId: c.goods?.id ?? 0,
                                            skuId: c.skuId,
                                            name: c.goods?.name ?? '',
                                            imageUrl: c.goods?.imageUrl ?? '',
                                            price: c.price,
                                            quantity: c.quantity,
                                            merchantId:
                                                c.goods?.merchantId ?? 0,
                                          ),
                                        )
                                        .toList();
                                    Get.toNamed(
                                      '/order',
                                      arguments: orderItems,
                                    );
                                  }
                                : null,
                            child: Text('去结算(${selectedCount})'),
                          ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
